import _ from 'lodash';
import Cls from 'classnames';
import { Button, Table, Row, message, Spin, Tabs, Space } from 'antd';
import { Fragment, useState, useContext, useEffect, useMemo, useCallback } from 'react';

import ExpertsListModal from './ExpertsListModal';
import ExpertsAddDeputyModal from './ExpertsAddDeputyModal';
import { SourceUpdateContext } from '../common/UpdateContext';
import { getExpertsColumns, getBidColumns } from '../mconfig';
import { CQXG_STATE, splitExpertData } from '../common/Format';
import { ApplyIdGetExpertDataGrid, BatchAddExpertsServices, addExpertsSerivice, editExpertsSerivice, getExpertsSerivice } from '../services/UpdateService';

import { DiffOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';

/**
 * @UpdateSourceExpertsView 评标专家
 * @returns
 */
const UpdateSourceExpertsView = () => {
  const { Invite_PackList, Source_Invite, curRes, locationProps } = useContext(SourceUpdateContext); /**上下文*/
  const { type, info } = locationProps?.state || {}; /**获取路由信息*/

  const [allList, setAllList] = useState<Record<string, any>[]>([]); /**数据总集合*/
  const [isShowExpertsState, setIsShowExpertsState] = useState(false); /**选择评标专家弹窗渲染状态*/
  const [isShowBidState, setIsShowBidState] = useState(false); /**添加采购人评标代表弹窗渲染状态*/
  const [isShowRemoveModal, setIsShowRemoveModal] = useState<Record<string, any>>({}); /**是否显示【删除采购人评标专家弹窗】*/
  const [isShowRemoveExpertModal, setIsShowRemoveExpertModal] = useState<Record<string, any>>({}); /**是否显示【删除评标专家弹窗】*/
  const [selectKey, setSelectKey] = useState<string>(Invite_PackList?.[0]?.id); /**tab选择项*/
  const [PackIndex, setPackIndex] = useState<number>(0); /**保存选择标包的下标*/
  const [ExpertData, setExpertData] = useState<Record<string, any>[]>([]);
  // const [isShowExtractModal, setIsShowExtractModal] = useState(false);/**是否显示 【抽取专家弹窗】*/

  /**根据申请ID获取采购人评标代表数据*/
  const { ApplyIdGetExpertRun, ApplyIdGetExpertLoading } = ApplyIdGetExpertDataGrid(curRes);
  const getExpertDataGird = async (id) => {
    const returnBody = await ApplyIdGetExpertRun({ applyID: id });
    setExpertData(returnBody?.rows || []);
  };

  /** 详情 */
  const { getExpertsRun, getExpertsLoading } = getExpertsSerivice((res, isFlagState) => {
    if (res?.msgFlag) {
      let { rows } = res;
      let new_allList = _?.cloneDeep(allList);
      let packIndex = new_allList?.findIndex((item) => item?.sourceID == selectKey);
      setPackIndex(packIndex);
      if (!isFlagState) {
        new_allList[packIndex].mpurchaseSourceExpertList = [...rows];
      }
      if (!new_allList[packIndex].nowMpurchaseSourceExpertList?.length || isFlagState) {
        // 如果length不存在 说明刚进入/没有详情请求/就没有数据
        if (isFlagState) {
          rows?.forEach((item) => {
            delete item?.['id'];
          });
        }
        new_allList[packIndex].nowMpurchaseSourceExpertList = [...rows];
      }
      setAllList(new_allList);
    } else {
      message.error(res?.msg);
    }
  }, curRes);

  /** 暂存(单个) */
  const { addExpertsRun, addExpertsLoading } = addExpertsSerivice((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      getExpertsRun({ sourceID: res?.obj });
    } else {
      message.error(res.msg);
    }
  });

  /** 暂存(多个) */
  const { BatchAddExpertsRun } = BatchAddExpertsServices((res) => {
    if (res?.msgFlag) {
      getExpertsRun({ sourceID: selectKey });
    }
  });

  /** 编辑 */
  const { editExpertsRun, editExpertsLoading } = editExpertsSerivice((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      getExpertsRun({ sourceID: res?.obj });
    } else {
      message.error(res.msg);
    }
  });

  /** 是否显示操作按钮 */
  const isShowOpenBtn = useMemo(() => {
    if (type == 'detail') return false;
    if (!Invite_PackList || !Invite_PackList?.length) return false;
    if (
      Invite_PackList[PackIndex]?.state == CQXG_STATE() &&
      allList?.[PackIndex]?.mpurchaseSourceExpertList?.length == 0 &&
      curRes?.['/purchaseSourceExpertController/addExpert']
    ) {
      return true;
    }

    if (
      Invite_PackList[PackIndex]?.state == CQXG_STATE() &&
      allList?.[PackIndex]?.mpurchaseSourceExpertList?.length &&
      curRes?.['/purchaseSourceExpertController/edit']
    ) {
      return true;
    }

    // if ()
    return false;
  }, [Invite_PackList, PackIndex, curRes, type, allList]);

  /** 采购人评标代表弹窗保存事件 */
  const onSaveBidData = (value: Record<string, any>) => {
    let new_allList = _?.cloneDeep(allList);
    const packExpertList = new_allList?.[PackIndex]?.nowMpurchaseSourceExpertList;
    packExpertList?.push({ ...value, sourceType: 1 });
    setAllList(new_allList);
  };

  /** 评标专家弹窗保存事件 */
  const onSaveExpertsData = (value: Record<string, any>[]) => {
    let new_allList = _?.cloneDeep(allList);
    new_allList[PackIndex].nowMpurchaseSourceExpertList = [...new_allList?.[PackIndex]?.nowMpurchaseSourceExpertList, ...value];
    setAllList(new_allList);
  };

  /** 移除专家 */
  const onRemoveExperts = (record, index: number) => {
    setIsShowRemoveExpertModal({
      isShow: true,
      resObj: record,
      recordIndex: index,
    });
  };

  /** 移除评标人代表 */
  const onRemoveBid = (record, index: number) => {
    setIsShowRemoveModal({
      isShow: true,
      resObj: record,
      recordIndex: index,
    });
  };

  /** 评标专家抛出事件 */
  const methods = {
    setValues: (_: Record<string, any>[]) => {},
  };

  /** 初始key值保存 */
  useEffect(() => {
    if (Invite_PackList?.[0]?.id) {
      const selectedInfo = Invite_PackList?.find((item) => item?.id === info?.id);
      const result = Invite_PackList?.find((item) => item?.id == selectKey);
      if (!result) {
        /** 采购实施管理页点击澄清按钮或者查看详情进来后默认选中对应的包-左侧tab栏 */
        if (selectedInfo?.id) {
          setSelectKey(selectedInfo?.id);
          return;
        }
        setSelectKey(Invite_PackList?.[0]?.id);
      } else {
        setSelectKey(result?.id);
      }
    }
  }, [Invite_PackList]);

  /** 初始化仓库 */
  useEffect(() => {
    if (Invite_PackList?.length && Source_Invite?.id) {
      const n_allList = Invite_PackList?.map((item, index, arr) => {
        // 形成一个总集合
        let record: Record<string, any> = {
          packID: item?.id,
          sourceID: item?.id,
          mpurchaseSourceExpertList: [],
          nowMpurchaseSourceExpertList: [],
        };
        if (index == 0 && arr?.length > 1) {
          record.isSync = 0;
        } // 第一个包
        else {
          record.isOtherSync = 0;
        } // 第二个包及以后的
        return record;
      });
      setAllList(n_allList);
      if (Source_Invite?.applyID) {
        getExpertDataGird(Source_Invite?.applyID);
      }
    }
  }, [Invite_PackList, Source_Invite]);

  /** key值改变触发接口 */
  useEffect(() => {
    if (selectKey) {
      getExpertsRun({ sourceID: selectKey });
    } // 详情接口
  }, [selectKey, Invite_PackList]);

  /** 刷新详情 */
  const reloadExpertsDetail = () => {
    getExpertsRun({ sourceID: selectKey }); // 详情接口
  };

  /** loading集合 */
  const allLoading = useMemo(() => {
    return addExpertsLoading || getExpertsLoading || editExpertsLoading || ApplyIdGetExpertLoading;
  }, [addExpertsLoading, getExpertsLoading, editExpertsLoading, ApplyIdGetExpertLoading]);

  /** 切换左侧tab */
  const changeTabs = useCallback(
    (value) => {
      setSelectKey(value);
      let page = Invite_PackList?.findIndex((item) => item?.id == value);
      setPackIndex(page);
      // formMethods?.setFieldsValue({
      //   selectPack: allList?.[page]?.selectPack,
      //   isSync: allList?.[page]?.isSync,
      //   isOtherSync: allList?.[page]?.isOtherSync,
      // });
    },
    [allList, PackIndex], //formMethods
  );

  /** 返回寻源专家卡片 */
  const container = () => {
    return (
      <Fragment>
        <Spin spinning={allLoading}>
          <div className={'source-experts'}>
            {Invite_PackList?.length > 0 && (
              <div className={Cls('source-experts-tabs', 'source-tabs-color')}>
                <Tabs
                  tabPosition={'left'}
                  items={Invite_PackList?.map((item) => {
                    return { label: item?.packCode, key: item?.id };
                  })}
                  onChange={(value) => changeTabs(value)}
                  activeKey={selectKey}
                />
              </div>
            )}

            <ScrollBarLayout>
              <div className={'source-experts-desc'}>
                {/* 暂时注释 */}
                {/* <Descriptions config={config} /> */}
                <div className={'source-experts-row'}>
                  <Row key={'experts'}>
                    <div className={'source-experts-item-title'}>一、采购人评标代表</div>
                    <div className={'list-table'}>
                      <Table
                        bordered
                        size="small"
                        columns={getBidColumns({
                          onRemove: onRemoveBid,
                          onOpen: () => setIsShowBidState(true),
                          isShowOpenBtn,
                        })}
                        dataSource={ExpertData}
                        // dataSource={splitExpertData(allList?.[PackIndex]?.nowMpurchaseSourceExpertList, 1)}
                        loading={false}
                        scroll={{ x: 550 }}
                        pagination={false}
                        rowKey={'id'}
                      />
                    </div>
                  </Row>
                  <Row key={'bid'} className={'source-experts-row-bid'}>
                    <div className={'source-experts-item-title'}>二、评标专家代表</div>
                    <div className={'list-table'}>
                      <Table
                        bordered
                        size="small"
                        columns={getExpertsColumns({
                          onRemove: onRemoveExperts,
                          onOpen: () => setIsShowExpertsState(true),
                          isShowOpenBtn,
                        })}
                        dataSource={splitExpertData(allList?.[PackIndex]?.nowMpurchaseSourceExpertList, 0)}
                        loading={false}
                        scroll={{ x: 500 }}
                        pagination={false}
                        rowKey={'id'}
                      />
                    </div>
                  </Row>
                </div>
              </div>
            </ScrollBarLayout>
          </div>

          {/* 添加采购人代表弹窗 */}
          {isShowBidState && <ExpertsAddDeputyModal onSave={onSaveBidData} onClose={() => setIsShowBidState(false)} />}

          {/* 选择专家弹窗 */}
          {isShowExpertsState && (
            <ExpertsListModal
              onSave={onSaveExpertsData}
              onClose={() => setIsShowExpertsState(false)}
              dataSource={splitExpertData(allList?.[PackIndex]?.nowMpurchaseSourceExpertList, 0)}
              curRes={curRes}
              // setIsShowExtractModal={(value: any) => {
              //   setIsShowExtractModal(value);
              // }}
            />
          )}

          {/** 抽取专家弹窗 */}
          {/* {isShowExtractModal && <ExtractListModal onClose={() => setIsShowExtractModal(false)} />} */}

          {/* 删除采购人评标代表弹窗 */}
          {isShowRemoveModal?.isShow && (
            <TipsErrorModalNew
              modalTip={
                <>
                  <span>
                    <p>
                      是否删除，姓名为【<span style={{ color: 'red' }}>{isShowRemoveModal?.resObj?.fullName}</span>
                      】的采购人评标代表
                    </p>
                    <p>注意：此操作不可恢复</p>
                  </span>
                </>
              }
              modalLoading={false}
              tipTextColor={'#000'}
              bodyWidth={0.25}
              modalTitle="删除采购人评标代表"
              onClose={() => setIsShowRemoveModal({})}
              modalOnOK={() => {
                let new_allList = _?.cloneDeep(allList);
                const packExpertList = new_allList?.[PackIndex]?.nowMpurchaseSourceExpertList;
                const delIndex = packExpertList?.findIndex((item) => {
                  if ('id' in item && 'id' in isShowRemoveModal?.resObj) {
                    return item?.id == isShowRemoveModal?.resObj?.id;
                  } else if ('mockID' in item && 'mockID' in isShowRemoveModal?.resObj) {
                    return item?.mockID == isShowRemoveModal?.resObj?.mockID;
                  }
                });
                packExpertList.splice(delIndex, 1);
                setAllList(new_allList);
              }}
            />
          )}

          {/* 删除评标专家弹窗 */}
          {isShowRemoveExpertModal?.isShow && (
            <TipsErrorModalNew
              modalTip={
                <>
                  <span>
                    <p>
                      是否删除，姓名为【<span style={{ color: 'red' }}>{isShowRemoveExpertModal?.resObj?.fullName}</span>
                      】的评标专家
                    </p>
                    <p>注意：此操作不可恢复</p>
                  </span>
                </>
              }
              modalLoading={false}
              tipTextColor={'#000'}
              bodyWidth={0.25}
              modalTitle="删除评标专家"
              onClose={() => setIsShowRemoveExpertModal({})}
              modalOnOK={() => {
                let new_allList = _?.cloneDeep(allList);
                const packExpertList = new_allList?.[PackIndex]?.nowMpurchaseSourceExpertList;
                const delIndex = packExpertList?.findIndex((item) => {
                  if ('id' in item && 'id' in isShowRemoveExpertModal?.resObj) {
                    return item?.id == isShowRemoveExpertModal?.resObj?.id;
                  } else if ('mockID' in item && 'mockID' in isShowRemoveExpertModal?.resObj) {
                    return item?.mockID == isShowRemoveExpertModal?.resObj?.mockID;
                  }
                });
                packExpertList.splice(delIndex, 1);
                setAllList(new_allList);
              }}
            />
          )}
        </Spin>
      </Fragment>
    );
  };

  /** 底部操作 */
  const btnFooter = () => {
    return (
      <Space>
        {isShowOpenBtn && type != 'detail' && (
          <Button
            type="primary"
            // icon={<DiffOutlined />}
            onClick={() => {
              let { applyID, projectID, projectCode, projectName, projectSum, purchProjectName, purchProjectCode } = Source_Invite;

              let result = {
                applyID,
                projectID,
                projectCode,
                projectName,
                projectSum,
                purchProjectName,
                purchProjectCode,
                sourceID: allList?.[PackIndex]?.sourceID,
                mpurchaseSourceExpertList: allList?.[PackIndex]?.nowMpurchaseSourceExpertList,
              };

              if (allList?.[PackIndex]?.mpurchaseSourceExpertList?.length == 0) {
                addExpertsRun(result); //单个添加
              } else {
                /**bottom的删除id*/
                let delIds: any[] = [];
                let old_data = allList?.[PackIndex]?.mpurchaseSourceExpertList;
                let allIds = allList?.[PackIndex]?.nowMpurchaseSourceExpertList?.map((item) => item?.id);

                old_data?.forEach((item) => {
                  if (!allIds?.includes(item?.id)) {
                    delIds?.push(item?.id);
                  }
                });

                let resObj = { ...result, delIds: delIds?.join(','), versionNum: old_data?.[0]?.versionNum };

                /**单个编辑*/
                editExpertsRun(resObj);
              }
            }}
          >
            暂存
          </Button>
        )}
      </Space>
    );
  };

  return {
    UpdateSourceExperts: container,
    SourceExpertsFooter: btnFooter,
    SourceExpertsMethods: methods,
    reloadExpertsDetail,
  };
};

export default UpdateSourceExpertsView;
